import { defineStore } from "pinia";
// import { generateExaminationApi } from "@/http/mockApi/students/examinationApi";
import { generateExaminationApi } from "@/http/Api/students/examinationApi";
import type { GenerateExaminationApiProps } from "@/http/mockApi/students/examinationApi";
// import { aesEncrypt, aesDecrypt } from "@/utils/aes";
import { shuffle } from "@/utils/shuffle";
import { useStore } from "./index";
import { formateTimeMS } from "@/utils/utils";

export const useExaminationStore = defineStore("examination", {
  state: () => {
    const questionId = localStorage.getItem("questionId");
    const questionsCollection = JSON.parse(
      localStorage.getItem("questionsCollection") || "{}"
    );
    let questionTotal;
    if (questionId) {
      questionTotal = questionsCollection[questionId];
    } else {
      questionTotal = {
        id: 0, // 考题 id
        allquestion: [],
        score: 0, // 最高分
        time: 0, // 开始考试时间
        endTime: 0, // 结束考试时间
        count: 1, // 试卷考试次数
        levelArrayId: [], // 考试难度
        type: "日考", // 考试类型
        title: "考试标题", // 考试标题
        stuId: 0, // 当前考题学生 id
        examCount: 0, //考题数量
        examTypeId: 0, // 考试类型编号
        subjectId: 0, // 学科方向
      };
    }

    return {
      recordId: localStorage.getItem("recoredId"), //后端返回考卷ID，暂空
      questionId, // 当前考题 id
      questionTotal, // 当前考题 {}
    };
  },
  getters: {
    // getAllquestion(state) {
    //   // 未开启
    //   if (state.recordId) {
    //     const cipherAllquestion = localStorage.getItem("cipherAllquestion");
    //     const allquestionStr = aesDecrypt(cipherAllquestion!); // 解码
    //     return JSON.parse(allquestionStr);
    //   } else {
    //     return [];
    //   }
    // },
    getTimeDiff(state) {
      const diff = state.questionTotal.endTime - state.questionTotal.time;
      return formateTimeMS(Math.ceil(diff / 1000));
    },
    calculateScore(state) {
      const totalCount = state.questionTotal.allquestion.length;
      // console.log("suanen 总数", totalCount);
      let correctTotal = 0;
      const oneScore = 100 / totalCount;
      for (let i = 0; i < totalCount; i++) {
        if (state.questionTotal.allquestion[i].type === "单选题") {
          // 单选题
          if (
            state.questionTotal.allquestion[i].answer &&
            state.questionTotal.allquestion[i].answer.join("") ==
              state.questionTotal.allquestion[i].correct.join("")
          ) {
            correctTotal += 1;
          }
        } else if (state.questionTotal.allquestion[i].type === "多选题") {
          if (
            state.questionTotal.allquestion[i].answer?.sort().join("") ==
            state.questionTotal.allquestion[i].correct.join("")
          ) {
            correctTotal += 1;
          }
        } else if (state.questionTotal.allquestion[i].type === "判断题") {
          if (
            state.questionTotal.allquestion[i].answer &&
            state.questionTotal.allquestion[i].answer.join("") ==
              state.questionTotal.allquestion[i].correct.join("")
          ) {
            correctTotal += 1;
          }
        }
      }
      const score = Math.floor(oneScore * correctTotal);

      return { totalCount, correctTotal, score };
    },
  },
  actions: {
    // 生成试卷
    async createExaminationAction(data: GenerateExaminationApiProps) {
      const examination = await generateExaminationApi(data);
      // console.log("获取到生成试卷：", examination.data);

      if (examination.data.code == "50000") {
        return Promise.reject(examination.data.msg);
      }
      if (
        examination.data.code == "200" &&
        examination.data.data.questions.length == 0
      ) {
        return Promise.reject("暂无题库，请联系班主任或者项目经理");
      }

      const shuffleExamination = shuffle(examination.data.data.questions);
      // console.log("打乱试卷：", shuffleExamination);

      const userstore = useStore();
      // console.log("当前用户id：", userstore.user.userId);

      this.recordId = examination.data.data.recordId;
      localStorage.setItem("recordId", examination.data.data.recordId);

      // 加密
      // const allquestionStr = JSON.stringify(shuffleExamination);
      // const cipherAllquestion = aesEncrypt(allquestionStr); // 对称加密
      // localStorage.setItem("cipherAllquestion", cipherAllquestion);

      // // 不加密
      // this.questionTotal.allquestion = shuffleExamination;
      // 目前题库保存在本地，通过时间戳来保存每次的题库
      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );

      // 判断是否已经超出10条数据，只保存最近10次考试记录
      // console.log("本地考试历史记录：", questionsCollection);
      const keys = Object.keys(questionsCollection);
      // console.log("目前本地考试记录条数：", keys);
      if (keys.length >= 10) {
        // ...
        delete questionsCollection[keys[0]];
      }
      const t = Date.now();
      // console.log("生成试卷时间：", t);

      const cuQuestionTotal = {
        id: t,
        allquestion: shuffleExamination, // 本次试题集
        score: 0, // 最高分
        time: t, // 开始考试时间
        endTime: t, // 结束考试时间
        count: 1, // 试卷考试次数
        levelArrayId: data.levelArrayId, // 考试难度
        type: "日考", // 考试类型
        title: "考试标题", // 考试标题
        stuId: userstore.user.userId, // 当前考题学生 id
        examCount: data.examCount, //考题数量
        examTypeId: data.examTypeId, // 考试类型编号
        subjectId: data.subjectId, // 学科方向
      };
      this.questionId = t.toString();
      this.questionTotal = cuQuestionTotal;

      questionsCollection[t] = cuQuestionTotal;
      // console.log("xiugaijilu --", questionsCollection);
      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );
      localStorage.setItem("questionId", t.toString()); // 本次考题生成时间，即考题保存 id

      // this.userId = userData.data.userId;
    },
    // 重新生成试卷
    async createExaminationActionAgain(id: number) {
      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );
      const q = questionsCollection[id];
      // console.log("要重新生成的试卷", q, id);

      try {
        const examination = await generateExaminationApi({
          examCount: q.examCount,
          examTypeId: q.examTypeId,
          levelArrayId: q.levelArrayId,
          stuId: q.stuId,
          subjectId: q.subjectId,
        });

        // console.log("重新生成试卷结果：", examination.data);

        if (examination.data.code == "50000") {
          return Promise.reject(examination.data.msg);
        }
        if (
          examination.data.code == "200" &&
          examination.data.data.questions.length == 0
        ) {
          return Promise.reject("暂无题库，请联系班主任或者项目经理");
        }

        const shuffleExamination = shuffle(examination.data.data.questions);

        const t = Date.now();
        q.count = q.count + 1;
        q.allquestion = shuffleExamination;
        q.time = t;
        q.endTime = t;
        this.questionTotal = q;
        this.questionId = String(id);

        questionsCollection[id] = q;

        localStorage.setItem(
          "questionsCollection",
          JSON.stringify(questionsCollection)
        );
        localStorage.setItem("questionId", String(id));
      } catch (err) {
        console.log("重新生成试卷失败", err);
        return Promise.reject("重新生成试卷失败");
      }
    },
    // 设置学生答案
    setAnswer(id: number, answer: any) {
      const index = this.questionTotal.allquestion.findIndex(
        (item: any) => item.id == id
      );
      // console.log("下标：", index, this.questionTotal.allquestion[index]);
      this.questionTotal.allquestion[index].answer = answer;

      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );
      questionsCollection[this.questionId as string].allquestion =
        this.questionTotal.allquestion;

      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );
    },
    // 重设置考题 id - 重做原来的题
    setQuestionId(id: string) {
      this.questionId = id;
      localStorage.setItem("questionId", id);

      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );

      questionsCollection[id].allquestion.forEach((item: any) => {
        const time = Date.now();
        item.answer = null;
        item.score = 0;
        item.time = time;
        item.endTime = time;
      });
      // console.log("现在考题-清空了答案 ", questionsCollection[id].allquestion);
      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );

      this.questionTotal = questionsCollection[id];
    },
    // 设置考题 - 查看答案
    setQuestionIdForAnswer(id: string) {
      console.log("查看答案");
      this.questionId = id;
      localStorage.setItem("questionId", id);

      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );

      this.questionTotal = questionsCollection[id];
    },
    // 设置考题考试次数
    setCount(id: string) {
      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );
      questionsCollection[id].count = questionsCollection[id].count + 1;
      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );
    },
    // 设置分数
    setScore() {
      const score = this.calculateScore.score;
      // console.log("获取分数", score);

      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );
      if (questionsCollection[this.questionId!].score) {
        if (score > questionsCollection[this.questionId!].score) {
          questionsCollection[this.questionId!].score = score;
        }
      } else {
        questionsCollection[this.questionId!].score = score;
      }
      // console.log("设置分数", score, questionsCollection);
      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );
      this.questionTotal.score = score;
    },
    // 设置考试结束时间
    setTime(time: any) {
      const questionsCollection = JSON.parse(
        localStorage.getItem("questionsCollection") || "{}"
      );
      questionsCollection[this.questionId!].endTime = time;
      // console.log("设置结束时间", time, questionsCollection);
      localStorage.setItem(
        "questionsCollection",
        JSON.stringify(questionsCollection)
      );

      this.questionTotal.endTime = time;
    },
  },
});
